// https://gist.github.com/si458/8571e8435f0bf6ece31c118e459ab780  文档

if (process.argv[2] === undefined) process.exit(0);
if (process.argv[2] === '') process.exit(0);
const {
  pkg_fetch_version, node_version, pkg_cache_path, icon,
  version, description, company, name, copyright, file,
} = require(`./${process.argv[2]}.json`);

const ResEdit = require('resedit');
const path = require('path');
const fs = require('fs');

process.env.PKG_CACHE_PATH = path.join(__dirname, pkg_cache_path);
const pkg_fetch = path.join(process.env.PKG_CACHE_PATH, `v${pkg_fetch_version}`);
const fetched = path.join(pkg_fetch, `fetched-v${node_version}-win-x64`);
const built = path.join(pkg_fetch, `built-v${node_version}-win-x64`);

const { exec } = require('pkg');

(async () => {
  if (!fs.existsSync(fetched)) {
    console.error('pkg fetch 文件不存在');
    process.exit(1);
  } else {
    console.log('Using Existing File');
  }
  console.log('Reading EXE');
  const data = fs.readFileSync(fetched);
  const exe = ResEdit.NtExecutable.from(data);
  const res = ResEdit.NtExecutableResource.from(exe);
  const viList = ResEdit.Resource.VersionInfo.fromEntries(res.entries);
  console.log(viList[0].data.strings);
  const vi = viList[0];
  const theversion = `${version}.0`.split('.');
  console.log('Removing OriginalFilename');
  vi.removeStringValue({ lang: 1033, codepage: 1200 }, 'OriginalFilename');
  console.log('Removing InternalName');
  vi.removeStringValue({ lang: 1033, codepage: 1200 }, 'InternalName');
  console.log('Setting Product Version');
  vi.setProductVersion(theversion[0], theversion[1], theversion[2], theversion[3], 1033);
  console.log('Setting File Version');
  vi.setFileVersion(theversion[0], theversion[1], theversion[2], theversion[3], 1033);
  console.log('Setting File Info');
  vi.setStringValues(
    { lang: 1033, codepage: 1200 },
    {
      FileDescription: description,
      ProductName: name,
      CompanyName: company,
      LegalCopyright: copyright,
    },
  );
  console.log(vi.data.strings);
  vi.outputToResourceEntries(res.entries);
  console.log('Replacing Icon');
  const iconFile = ResEdit.Data.IconFile.from(fs.readFileSync(path.join(__dirname, icon)));
  ResEdit.Resource.IconGroupEntry.replaceIconsForResource(
    res.entries,
    1,
    1033,
    iconFile.icons.map((item) => item.data),
  );
  res.outputResource(exe);
  console.log('Generating EXE');
  const newBinary = exe.generate();
  console.log('Saving EXE');
  fs.writeFileSync(built, Buffer.from(newBinary));
  console.log('Bundling App');
  await exec(['--build', '--config', `${process.argv[2]}.json`, `${file}`, '--output', 'local-interface.exe']);
})();
